import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Typography,
  List,
  Avatar,
  Tag,
  Progress,
  Space,
} from 'antd';
import {
  UserOutlined,
  TeamOutlined,
  CrownOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import type { User } from '../types';
import { mockUserAPI } from '../utils/mockData';

const { Title, Text } = Typography;

const Dashboard: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await mockUserAPI.getUsers({ current: 1, pageSize: 100 });
        setUsers(result.data);
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // 统计数据
  const stats = {
    total: users.length,
    active: users.filter(u => u.status === 'active').length,
    admin: users.filter(u => u.role === 'admin').length,
    inactive: users.filter(u => u.status === 'inactive').length,
  };

  // 活跃度百分比
  const activeRate = stats.total > 0 ? (stats.active / stats.total) * 100 : 0;

  // 最近活跃用户
  const recentUsers = users
    .filter(u => u.status === 'active')
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
    .slice(0, 5);

  // 系统状态
  const systemStatus = [
    { name: '用户服务', status: 'normal', value: '正常' },
    { name: '数据库', status: 'normal', value: '正常' },
    { name: '缓存服务', status: 'warning', value: '警告' },
    { name: '文件存储', status: 'normal', value: '正常' },
  ];

  return (
    <div>
      <Title level={2}>信息</Title>
      
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={stats.total}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={stats.active}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="管理员"
              value={stats.admin}
              prefix={<CrownOutlined />}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card>
            <Statistic
              title="非活跃用户"
              value={stats.inactive}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        {/* 活跃度进度 */}
        <Col xs={24} lg={12}>
          <Card title="用户活跃度" loading={loading}>
            <div style={{ marginBottom: 16 }}>
              <Text>当前活跃率</Text>
              <Progress
                percent={Math.round(activeRate)}
                status={activeRate > 80 ? 'success' : activeRate > 60 ? 'normal' : 'exception'}
                style={{ marginTop: 8 }}
              />
            </div>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Text>活跃用户</Text>
                <Text strong>{stats.active}</Text>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Text>总用户数</Text>
                <Text strong>{stats.total}</Text>
              </div>
            </Space>
          </Card>
        </Col>

        {/* 系统状态 */}
        <Col xs={24} lg={12}>
          <Card title="系统状态" loading={loading}>
            <List
              dataSource={systemStatus}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar
                        icon={
                          item.status === 'normal' ? (
                            <CheckCircleOutlined />
                          ) : (
                            <ExclamationCircleOutlined />
                          )
                        }
                        style={{
                          backgroundColor: item.status === 'normal' ? '#52c41a' : '#faad14',
                        }}
                      />
                    }
                    title={item.name}
                    description={
                      <Tag color={item.status === 'normal' ? 'green' : 'orange'}>
                        {item.value}
                      </Tag>
                    }
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>

      {/* 最近活跃用户 */}
      <Card title="最近活跃用户" style={{ marginTop: 16 }} loading={loading}>
        <List
          dataSource={recentUsers}
          renderItem={(user) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Space>
                    {user.username}
                    {user.role === 'admin' && (
                      <CrownOutlined style={{ color: '#faad14' }} />
                    )}
                    <Tag color={user.status === 'active' ? 'green' : 'orange'}>
                      {user.status === 'active' ? '活跃' : '非活跃'}
                    </Tag>
                  </Space>
                }
                description={user.email}
              />
              <div>
                <Text type="secondary">
                  最后更新: {new Date(user.updatedAt).toLocaleDateString()}
                </Text>
              </div>
            </List.Item>
          )}
        />
      </Card>
    </div>
  );
};

export default Dashboard; 